<?php
namespace app\admin\controller;
use cmf\controller\AdminBaseController;
use think\Db;
use think\Loader;
use think\Request;

class ApplynumbersController extends AdminBaseController
{
	public function index()
	{
		$content = hook_one('admin_applynumbers_index_view');
		if (!empty($content)) {
			return $content;
		}

		$where = ['id' => ['neq', 0]];
		/**搜索条件**/
		$apply_name = $this->request->param('apply_name');
		if ($apply_name) {
			$where['apply_name'] = ['like', "%$apply_name%"];
		}

		$applynumbersList = Db::name('applynumbers')
			->where($where)
			->order("id DESC")
			->paginate(50);

		$applynumbersList->appends(['apply_name' => $apply_name]);
		// 获取分页显示
		$page = $applynumbersList->render();

		$this->assign("page", $page);
		$this->assign($this->myconfig($id=''));
		$this->assign("applynumbersList", $applynumbersList);
		return $this->fetch();
	}

	public function add()
	{
		$this->assign($this->myconfig($id=''));
		return $this->fetch();
	}

	public function addPost()
	{
		if ($this->request->isPost()) {
			if (!empty($_POST['apply_name'])) {
				$_POST["create_time"] = date("Y-m-d H:i:s");
				$_POST["update_time"] = date("Y-m-d H:i:s");

				if(isset($_POST['apply_one_agent']) && $_POST['apply_one_agent']){
					$_POST['apply_one_agent'] = implode(',', $_POST['apply_one_agent']);
				}else{
					$_POST['apply_one_agent'] = '';
				}
				if(isset($_POST['apply_two_blong']) && $_POST['apply_one_blong']){
					$_POST['apply_two_blong'] = implode(',', $_POST['apply_one_blong']);
				}else{
					$_POST['apply_two_blong'] = '';
				}
				if(isset($_POST['apply_two_blong']) && $_POST['apply_two_blong']){
					$_POST['apply_two_blong'] = implode(',', $_POST['apply_two_blong']);
				}else{
					$_POST['apply_two_blong'] = '';
				}

				if($_POST['apply_image'] && $_POST['apply_image_bak1']){
					$_POST['apply_image'] = $_POST['apply_image_bak1'];
				}
				unset($_POST['apply_image_bak1']);
				$result	= DB::name('applynumbers')->insertGetId($_POST);
				if ($result !== false) {
						$this->success("添加成功！", url("applynumbers/index"));
					} else {
						$this->error("添加失败！");
					}
			} else {
				$this->error("公司名称能为空！");
			}
		}
	}

	public function edit()
	{
		$content = hook_one('admin_applynumbers_edit_view');

		if (!empty($content)) {
			return $content;
		}

		$id      = $this->request->param('id', 0, 'intval');
		$applynumbers = DB::name('applynumbers')->where(["id" => $id])->find();
		$this->assign($this->myconfig($id=''));
		$this->assign($applynumbers);
		return $this->fetch();
	}

	public function editPost()
	{
		if ($this->request->isPost()) {
			if (!empty($_POST['id'])) {
				$_POST["update_time"] = date("Y-m-d H:i:s");
				
				if(isset($_POST['apply_one_agent']) && $_POST['apply_one_agent']){
					$_POST['apply_one_agent'] = implode(',', $_POST['apply_one_agent']);
				}else{
					$_POST['apply_one_agent'] = '';
				}
				if(isset($_POST['apply_two_blong']) && $_POST['apply_one_blong']){
					$_POST['apply_two_blong'] = implode(',', $_POST['apply_one_blong']);
				}else{
					$_POST['apply_two_blong'] = '';
				}
				if(isset($_POST['apply_two_blong']) && $_POST['apply_two_blong']){
					$_POST['apply_two_blong'] = implode(',', $_POST['apply_two_blong']);
				}else{
					$_POST['apply_two_blong'] = '';
				}

				$result = DB::name('applynumbers')->update($_POST);
				if ($result !== false) {
						$this->success("添加成功！", url("applynumbers/index"));
					} else {
						$this->error("添加失败！");
					}
			} else {
				$this->error("ID不能为空！");
			}
		}
	}

	public function delete()
	{
		$id = $this->request->param('id', 0, 'intval');

		if (Db::name('applynumbers')->delete($id) !== false) {
			$this->success("删除成功！");
		} else {
			$this->error("删除失败！");
		}
	}

	public function myconfig($id){
		$myconfig = array(
			'apply_agent_config' => array('1'=>'飞书1', '2'=>'FSHY', '3'=>'FSSW', '4'=>'飞书4', '5'=>'木瓜1', '6'=>'木瓜2', '7'=>'猎豹', '8'=>'MV', '9'=>'superads', '10'=>'云克', '11'=>'赤子城', '12'=>'Ewaymobi', '13'=>'MenaMOBI', '14'=>'熊猫', '15'=>'clickmob', '16'=>'soclink', '17'=>'madehouse', '18'=>'蓝标', '19'=>'摩邑城', '20'=>'英宝通', '21'=>'MAD','22'=>'有道','23'=>'Indexmobi','24'=>'试玩互动'),

			'apply_main_status_config' => array(
				'0'=>'未选择',
				'1'=>'正常',
				'2'=>'黑名单',
				'3'=>'限制开户'
			)
		);
		return $myconfig;
	}


	public function exportfile(){
		if ($this->request->isPost()) {
			if (!empty($_POST['upload_filename'])) {
				if($_POST['upload_filename'] && $_POST['upload_filename_url1']){
					$_POST['upload_filename'] = $_POST['upload_filename_url1'];
				}
				$file_path = $_POST['upload_filename'];
				// echo $file_path;
				$this->dataexport($file_path);
			} else {
				$this->error("没有文件");
			}
		}
	}
	// 导入表格
    public function dataexport($file_path){
    	if(!$file_path){
    		 $this->error('没有上传文件');
    	}
    	$excelData = $this->excelRead($file_path); 

    	foreach ($excelData as $k => $v) {
    		if($k > 0){
    			$data['apply_name'] 		= isset($v[0]) ? $v[0] : '';
    			$data['apply_url'] 			= isset($v[1]) ? $v[1] : '';
    			$data['apply_one_agent'] 	= isset($v[2]) ? $v[2] : '1';
    			$data['apply_one_blong'] 	= isset($v[3]) ? $v[3] : '';
    			$data['apply_two_blong'] 	= isset($v[4]) ? $v[4] : '';
    			$data['apply_main_status'] 	= isset($v[5]) ? $v[5] : '1';
    			$data['apply_get_number'] 	= isset($v[6]) ? $v[6] : '';
    			$data['apply_done_number'] 	= isset($v[7]) ? $v[7] : '';
    			$data['apply_get_date'] 	= isset($v[8]) ? $v[8] : '';
    			$data['apply_done_date'] 	= isset($v[9]) ? $v[9] : '';
    			$data['apply_group'] 		= isset($v[10]) ? $v[10] : '';
    			$data['apply_user'] 		= isset($v[11]) ? $v[11] : '';
    			$data['apply_image'] 	= isset($v[12]) ? $v[12] : '';
    			$data['apply_remark'] 	= isset($v[13]) ? $v[13] : '';

    			$data['status'] 		= '1';
    			$data['isblack'] 		= '1';
    			$data['url_opt_uid'] 	= '1';
    			$data['create_time'] 	= date('Y-m-d H:i:s');
    			$data['update_time'] 	= date('Y-m-d H:i:s');

    			if($data['apply_name']){
    				 Db::name('applynumbers')->insert($data);
    			}
    			// else{
    			// 	$this->error("公司名称不能为空!", url("applynumbers/index"));
    			// }
    		}
    		// if($k > 2){
    		// 	$this->success('导入成功' , url("applynumbers/index"));
    		// }

    		// $this->success('导入成功' , url("applynumbers/index"));
         }
         $this->success('导入成功' , url("applynumbers/index"));
    }

    /**
     *读取excel数据
     *string $excel_url  excel路径
     *return array $excel_array 读取数组
     */
    public function excelRead($excel_url)
    {
        Loader::import('PHPExcel.Classes.PHPExcel');
        Loader::import('PHPExcel.Classes.PHPExcel.IOFactory.PHPExcel_IOFactory');
        Loader::import('PHPExcel.Classes.PHPExcel.Reader.Excel5');
        $filename = ROOT_PATH.'public/upload/'.$excel_url;  //文件路径
        $extension = cmf_get_file_extension($excel_url);    //文件扩展名

        if($extension == 'xlsx'){
            $objReader =\PHPExcel_IOFactory::createReader('Excel2007');
            $objPHPExcel = $objReader->load($filename, $encode = 'utf-8');  //加载文件内容,编码utf-8
        }else if($extension == 'xls'){
            $objReader =\PHPExcel_IOFactory::createReader('Excel5');
            $objPHPExcel = $objReader->load($filename, $encode = 'utf-8');  //加载文件内容,编码utf-8
        }else if($extension == 'csv'){
            
            $objReader = \PHPExcel_IOFactory::createReader('CSV')
                ->setDelimiter(',')  
                // ->setInputEncoding('GBK') //不设置将导致中文列内容返回boolean(false)或乱码   
                ->setEnclosure('"')  
                // ->setLineEnding("\r\n")  //新版本可删除 
                ->setSheetIndex(0); 
                $objPHPExcel = $objReader->load($filename, $encode = 'utf-8');
                
                // $excel_array = $objPHPExcel->getsheet(0)->toArray();   //转换为数组格式
                // // array_shift($excel_array);  //删除第一个数组(标题);
                // $excelArray = trimExcelStrBlank($excel_array);
                // var_dump($excelArray);
                // exit();
        }else{
            $this->error('请上传Excel格式的文件！','');
        }

        $excel_array = $objPHPExcel->getsheet(0)->toArray();   //转换为数组格式
        // array_shift($excel_array);  //删除第一个数组(标题);
        $excelArray = trimExcelStrBlank($excel_array);
        return TrimArray($excelArray);
        // return $excel_array;
    }
}
